package cn.itsource.jwt;

import org.springframework.util.StringUtils;

import java.security.PublicKey;

/**
 * 用户上下文工具类
 *  专门获取当前登录用户信息
 */
public class UserContext {

    //jwt请求头的名称
    public static final String JWT_TOKEN_HEADER_NAME = "U-TOKEN";

    /**
     * 获取当前登录用户信息
     * @param jwtToken 字符串
     * @return Login对象
     */
    public static Login getUser(String jwtToken){
        try {
            if(StringUtils.hasText(jwtToken)){
                //2.工具类解析JWT字符串
                //publicKey解密
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
                Payload<UserInfo> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, UserInfo.class);
                if(payload != null && payload.getUserInfo() != null){
                    return payload.getUserInfo().getLogin();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}